import type { FormRules, FormItemRule } from "element-plus";

export const REGEXP_PHONE = /^1[3-9]\d{9}$/;

const createPhoneFieldRules = (): FormItemRule[] => [
  { required: true, message: "请输入手机号", trigger: "blur" },
  {
    pattern: REGEXP_PHONE,
    message: "请输入有效的 11 位手机号",
    trigger: "blur"
  }
];

const createVerifyCodeRules = (): FormItemRule[] => [
  { required: true, message: "请输入短信验证码", trigger: "blur" },
  {
    min: 4,
    max: 6,
    message: "验证码长度需为 4-6 位",
    trigger: "blur"
  }
];

const createPasswordRules = (message = "请输入密码"): FormItemRule[] => [
  { required: true, message, trigger: "blur" },
  {
    min: 6,
    max: 32,
    message: "密码长度需在 6-32 位之间",
    trigger: "blur"
  }
];

export const phoneRules: FormRules = {
  phone: createPhoneFieldRules(),
  verifyCode: createVerifyCodeRules()
};

export const loginRules: FormRules = {
  phone: createPhoneFieldRules(),
  password: createPasswordRules("请输入密码")
};

type RegisterFormModel = {
  phone: string;
  verifyCode: string;
  password: string;
  confirmPassword: string;
  inviteCode?: string;
};

export const registerRules = (form: RegisterFormModel): FormRules => ({
  phone: createPhoneFieldRules(),
  verifyCode: createVerifyCodeRules(),
  password: createPasswordRules("请设置登录密码"),
  confirmPassword: [
    ...createPasswordRules("请再次输入密码"),
    {
      validator: (_rule, value, callback) => {
        if (!value) {
          callback(new Error("请再次输入密码"));
        } else if (value !== form.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  inviteCode: [
    {
      max: 20,
      message: "邀请码长度不超过 20 个字符",
      trigger: "blur"
    }
  ]
});

type UpdateFormModel = {
  phone: string;
  verifyCode: string;
  password: string;
  confirmPassword: string;
};

export const updateRules = (form: UpdateFormModel): FormRules => ({
  phone: createPhoneFieldRules(),
  verifyCode: createVerifyCodeRules(),
  password: createPasswordRules("请设置新密码"),
  confirmPassword: [
    ...createPasswordRules("请再次输入密码"),
    {
      validator: (_rule, value, callback) => {
        if (!value) {
          callback(new Error("请再次输入密码"));
          return;
        }
        if (value !== form.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
